package com.td.module.equipment.framework.core;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallbackExtended;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;

/**
 * @author zhanghe
 * @date 2023/4/16
 */

@Slf4j
@Data
public abstract class AbsMqttCallBack implements MqttCallbackExtended {


    private String clientId;

    private MqttConnectOptions mqttConnectOptions;

    @Override
    public void connectComplete(boolean b, String s) {
        log.info("==============ClientId:{}客户端连接成功！==============", clientId);
    }

    /**
     * 客户端断开连接的回调
     */
    @Override
    public void connectionLost(Throwable throwable) {
        log.info("ClientId:{}与服务器断开连接，可重连", clientId);
    }

    /**
     * 发布消息成功
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        log.info("ClientId:{}发送消息成功", clientId);
    }

    /**
     * 客户端收到消息触发
     */
    @Override
    public void messageArrived(String topic, MqttMessage message) {

        handleMessageArrived(topic, new String(message.getPayload()));

        log.info(String.format("ClientId%s接收消息主题 : %s", clientId, topic));
        log.info(String.format("ClientId%s接收消息Qos : %d", clientId, message.getQos()));
        log.info(String.format("ClientId%s接收消息内容 : %s", clientId, new String(message.getPayload())));
        log.info(String.format("ClientId%s接收消息retained : %b", clientId, message.isRetained()));
    }

    protected abstract void handleMessageArrived(String topic, String message);
}
